require 'yaml'
require 'rubygems'
require 'rake'
require 'rake/testtask'

require 'tools/generator'

task :default => :test

desc 'Test recent changes.'
Rake::TestTask.new(:test) do |t|
  t.libs << "test"
  t.test_files = FileList['test/test*.rb']
  t.verbose = true
end

desc 'Generate a new set of cluster data'
task :gen_grid do
  puts "Generating a new set of cluster data..."
  config = YAML.load(File.new('config.yml').read)['grid_clustering']

  puts config.inspect
  Digger::Generator::ClusterGrid.new(config['size'],
                                     config['dimensions'], config).
                                     write('data/clusters.csv')
  puts "Generation complete..."
end

desc 'Plot the latest distance data.'
task :dist_plot do
  puts "Plotting latest distance data..."

  require 'rubygems'
  require 'gnuplot'
  require 'faster_csv'

  Gnuplot.open do |gp|
    Gnuplot::Plot.new( gp ) do |plot|

      plot.title  "Inter-Cluster Distances"
      plot.ylabel "Avg. Distance"
      plot.xlabel "Simulation Time"

      time = []
      avg = []
      std = []
      FasterCSV.foreach("data/distances.csv", :converters => :float) do |row|
        time << row[0]
        avg << row[1]
        std << row[2]
      end

      plot.data << Gnuplot::DataSet.new( [time, avg, std] ) do |ds|
        ds.with = "yerrorlines"
        #ds.title = "Inter-Cluster Distance" 
      end
    end
  end
end

desc 'Plot the current cluster dataset in 2d.'
task :two_plot do
  puts "Plotting 2D clusters from data/clusters.csv"

  require 'rubygems'
  require 'gnuplot'
  require 'faster_csv'

  Gnuplot.open do |gp|
    Gnuplot::Plot.new( gp ) do |plot|

      plot.title  "Cluster Data"
      plot.ylabel "y"
      plot.xlabel "x"

      x = []
      y = []
      FasterCSV.foreach("data/clusters.csv", :converters => :float) do |row|
        x << row[0]
        y << row[1]
      end

      plot.data << Gnuplot::DataSet.new( [x, y] ) do |ds|
        ds.with = "points"
        ds.title = "Cluster Data"
      end
    end
  end
end

desc 'Plot the current cluster dataset in 3d.'
task :three_plot do
  puts "Plotting 3D clusters from data/clusters.csv"

  require 'rubygems'
  require 'gnuplot'
  require 'faster_csv'

  Gnuplot.open do |gp|
    Gnuplot::SPlot.new( gp ) do |plot|

      plot.title  "Cluster Data"
      plot.ylabel "y"
      plot.xlabel "x"

      class ClusterData
        def initialize
          @data = ''
          FasterCSV.foreach("data/clusters.csv", :converters => :float) do |row|
            @data << row.join(' ') + "\n"
          end
        end

        def to_gsplot
          @data
        end
      end

      plot.data << Gnuplot::DataSet.new( ClusterData.new ) do |ds|
        ds.with = "points"
        ds.title = "Cluster Data"
      end
    end
  end
end
